<template>
  <a-card>
    <a-row>
      <a-col :span="6">
        <div style="position:relative;top:0;left:20px;">
          <a-input-search
            v-model="searchValue"
            style="margin-bottom: 8px;width: 70%"
            placeholder="搜索"
            @change="searchTreeNode"
          />
        </div>
        <div style="height: 650px; overflow-y: scroll;margin: 0px 10px">
          <a-spin tip="加载中..." :spinning="spinning">
            <a-tree
              class="storage_tree"
              v-if="treeData"
              :replaceFields="{
              children: 'children',
              title: 'orgname',
              key: 'id',
            }"
              :tree-data="treeData"
              @select="onSelect"
            >
            </a-tree>
          </a-spin>
        </div>
      </a-col>
      <a-col :span="18">
        <div class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="48">
              <a-col :xxl="6" :lg="8" :sm="8">
                <a-form-item label="关联人员名称">
                  <a-input placeholder="请输入姓名" v-model="queryParam.u_name" />
                </a-form-item>
              </a-col>
              <a-col :md="(!advanced && 8) || 24" :sm="24">
                <span
                  class="table-page-search-submitButtons"
                  :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
                >
                  <a-button class="btn_primary_color accept_more_operate_right_submit" type="primary"
                            @click="searchDi_rel_dept_correct">
                  查询
                </a-button>
                <a-button class="btn_normal_color accept_more_operate_right_reset" type="primary" @click="flushedQuery">
                  重置
                </a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <a-table
          :scroll="{x: 550, y: 550 }"
          v-if="ddata"
          :columns="ucolumns"
          :data-source="ddata"
          :pagination="upagination"
          :loading="loading"
          @change="tableChange"
          rowKey="id"
          size="middle"
          :bordered="ubordered"
        >
          <span slot="serial" slot-scope="text, record, index">
            {{ (upagination.current - 1) * upagination.pageSize + parseInt(index) + 1 }}
          </span>
          <span slot="operation" slot-scope="text, record">
            <template>
              <a @click="handleEdit(record, false)">编辑</a>
            </template>
          </span>
          <div slot="careerranktextSlot" slot-scope="careerranktext" style="text-align: left">
            {{ careerranktext }}
          </div>
          <div slot="orgnameSlot" slot-scope="orgname" style="text-align: left" class="beyond_hiding">
            <a-tooltip placement="topLeft">
              <template slot="title">
                <span>{{ orgname }}</span>
              </template>
              {{ orgname }}
            </a-tooltip>
          </div>
        </a-table>
      </a-col>
    </a-row>
    <a-drawer
      :title="isView ? '部门详情' : '部门编辑'"
      :width="720"
      :visible="visible"
      :body-style="{ paddingBottom: '80px' }"
      @close="onClose"
    >
      <edit ref="view" @close="onClose" @reloadList="searchDi_rel_dept_correct"></edit>
    </a-drawer>
  </a-card>
</template>

<script>
import { getQueryTree, queryPageDeptAndUser } from '@/api/ding/di_rel_dept_correct.js'
import edit from '@/views/base/CorrectOrgEdit.vue'

export default {
  components: { edit },
  data () {
    return {
      searchValue: undefined, // 搜索值
      cloneTreeData: [], // 备份树节点数据
      spinning: false, // 树的遮罩
      advanced: false, // 查询条件是否展开
      loading: false, // 遮罩是否显示
      visible: false, // 抽屉是否可见
      ubordered: true, // 表格边框是否显示
      isView: false, // 是否查看
      treeData: [], // 查询树数据
      selectedKeys: [],
      queryParam: {
        f_id: null,
        u_name: null,
        f_orgname: null,
        pageNumber: undefined,
        pageSize: 20
      },
      ddata: [], // 表格数据,
      ucolumns:
        [
          {
            title: '序号',
            width: 50,
            key: 'index',
            align: 'center',
            fixed: 'left',
            scopedSlots: { customRender: 'serial' }
          },
          {
            title: '组织名称',
            dataIndex: 'orgname',
            key: 'orgname',
            align: 'center',
            width: 150,
            scopedSlots: { customRender: 'orgnameSlot' }
          },
          {
            title: '名称',
            dataIndex: 'username',
            key: 'username',
            align: 'center',
            width: 100
          },
          {
            title: '区域id',
            dataIndex: 'adid',
            key: 'adid',
            align: 'center',
            width: 150
          },
          {
            title: '联系电话',
            dataIndex: 'mobile',
            key: 'mobile',
            align: 'center',
            width: 150
          },
          {
            title: '性别',
            dataIndex: 'sextext',
            key: 'sextext',
            align: 'center',
            width: 90
          },
          {
            title: '岗位级别',
            dataIndex: 'careerranktext',
            key: 'careerranktext',
            align: 'center',
            width: 200,
            scopedSlots: { customRender: 'careerranktextSlot' }
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: 120,
            fixed: 'right',
            align: 'center',
            scopedSlots: { customRender: 'operation' }
          }
        ],
      upagination: {
        // 表格分页参数
        defaultPageSize: 20,
        total: 0,
        current: 1,
        pageSize: 20,
        showTotal: total => `共${total}条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100']
      }
    }
  },
  async created () {
    this.spinning = true
    this.loading = true
    await this.getValue()
    this.findDi_rel_dept_correctList(this.queryParam)
  },
  methods: {
    searchTreeNode () {
      const value = this.searchValue
      this.filter(this.treeData, value)
      if (value == '') {
        this.treeData = JSON.parse(JSON.stringify(this.cloneTreeData)) // cloneTreeData 接口返回深拷贝的数据
      }
    },
    filter (nodes, query) {
      // 条件就是节点的title过滤关键字
      const predicate = function (node) {
        if (node.orgname.indexOf(query) > -1) {
          return true
        } else {
          return false
        }
      }
      console.log('nodes', nodes)
      if (!(nodes && nodes.length)) {
        return []
      }
      console.log('nodes', nodes)
      const newChildren = []
      for (const node of nodes) {
        // 以下只需要考虑自身的节点满足条件即可,不用带上父节点
        if (predicate(node)) {
          newChildren.push(node)
          node.children = this.filter(node.children, query)
        } else {
          newChildren.push(...this.filter(node.children, query))
        }
      }
      this.treeData = newChildren // this.treeData接口返回的数组
      return newChildren.length ? newChildren : []
    },
    //查询部门列表
    findDi_rel_dept_correctList (queryParam) {
      const a = Date.now()
      this.ddata = []
      this.loading = true
      queryPageDeptAndUser(queryParam).then(res => {
        if (res.code === 0) {
          this.ddata = res.data.records
          // 将当前页码和数量与后台绑定绑定
          this.upagination.total = res.data.total
          this.upagination.current = res.data.current
          this.upagination.pageSize = res.data.size
          // 如果查询时间太短，延迟0.5
          const b = Date.now()
          if (b - a < 100) {
            setTimeout(() => {
              this.loading = false
            }, 100)
          } else {
            this.loading = false
          }
        } else {
          this.$message.error('查询失败')
        }
      })
    },
    getValue () {
      getQueryTree().then((res) => {
        if (res.code === 0) {
          this.treeData = res.data || []
          this.cloneTreeData = JSON.parse(JSON.stringify(this.treeData))
        }
      }).finally(() => {
        this.spinning = false
      })
    },
    /**
     * 翻页、设置页数量时触发，将分页组建的当前页与大小传给后台
     */
    tableChange (pagination, filters, sorter, { currentDataSource }) {
      this.queryParam.pageNumber = pagination.current
      this.queryParam.pageSize = pagination.pageSize
      if (sorter != null && sorter.order != null) {
        this.queryParam.sort = sorter.field
        this.queryParam.order = sorter.order
      }
      this.findDi_rel_dept_correctList(this.queryParam)
    },
    // 树选中
    onSelect (ks, data) {
      if (ks.length > 0) {
        this.queryParam.f_id = ks[0]
      } else {
        this.queryParam.f_id = null
      }
      this.searchDi_rel_dept_correct()
    },
    /**
     * 查询
     */
    searchDi_rel_dept_correct () {
      this.queryParam.pageNumber = 1
      this.findDi_rel_dept_correctList(this.queryParam)
    },
    /**
     * 重置查询条件并查询数据
     */
    flushedQuery () {
      this.queryParam = {
        f_id: null,
        u_name: null,
        f_orgname: null,
        pageNumber: undefined,
        pageSize: 20
      }
      this.findDi_rel_dept_correctList(this.queryParam)
    },
    /**
     * 进入编辑页面
     */
    handleEdit (res, isView) {
      this.isView = isView
      this.showDrawer()
      setTimeout(() => {
        this.$refs.view.findDeptAndUserById(res.id, isView)
      }, 10)
    },
    /**
     * 打开抽屉
     */
    showDrawer () {
      this.visible = true
    },
    /**
     * 收回抽屉
     */
    onClose () {
      this.visible = false
    }
  }

}
</script>

<style>

</style>
